package link.cocoon.common.base;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.MultiValueMap;

/**
 * @author xce
 * @version V1.0
 * @note 基础测试类.集成了 post，get等常用方法.待完善.
 * @package link.larva.system.controller
 * @date 2019/10/23 9:48
 */
@Slf4j
public abstract class BaseTestController {

  protected static MockMvc mockMvc;


  /**
   * 执行执行请求.
   *
   * @param httpMethod 请求方法.
   * @param url        请求路径.
   * @param params     参数.
   * @param mediaType  类型.
   * @return 返回的字符串
   */
  private String doRequest(HttpMethod httpMethod, String url, MultiValueMap<String, String> params, MediaType mediaType)
      throws Exception {
    return mockMvc.perform(request(httpMethod, url).params(params).contentType(mediaType)).andReturn().getResponse()
        .getContentAsString();
  }

  /**
   * 执行post请求.
   *
   * @param url    请求路径.
   * @param params 请求参数.
   * @return 返回的字符串
   */
  protected String doPost(String url, MultiValueMap<String, String> params) throws Exception {
    return doRequest(HttpMethod.POST, url, params, MediaType.APPLICATION_JSON);
  }

  /**
   * 执行get请求.
   *
   * @param url    请求路径.
   * @param params 请求参数.
   * @return 返回的字符串
   */
  protected String doGet(String url, MultiValueMap<String, String> params) throws Exception {
    return doRequest(HttpMethod.GET, url, params, MediaType.APPLICATION_JSON);
  }
}
